package com.yf.utils;


import com.alibaba.fastjson.JSONObject;
import org.apache.http.HttpEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.apache.commons.codec.binary.Base64;

import java.io.IOException;

public class HttpUtil {
    public static String post(String url, String json) {
        CloseableHttpClient client = HttpClients.createDefault();
        HttpPost httpPost = new HttpPost(url);
        httpPost.setHeader("Content-Type", "application/json");
        httpPost.setHeader("Accept", "application/json");
        StringEntity data = new StringEntity(json, ContentType.APPLICATION_JSON);
        httpPost.setEntity(data);
        try (CloseableHttpResponse response = client.execute(httpPost)) {
            return EntityUtils.toString(response.getEntity());
        } catch (IOException e) {
            return "";
        }
    }

    public static String post(String url) {
        CloseableHttpClient client = HttpClients.createDefault();
        HttpPost httpPost = new HttpPost(url);
        httpPost.setHeader("Content-Type", "application/x-www-form-urlencoded");
        try (CloseableHttpResponse response = client.execute(httpPost)) {
            return EntityUtils.toString(response.getEntity());
        } catch (IOException e) {
            return "";
        }
    }

    public static String sendEmail(String receiver, String subject, String content) {
        final String authStr = "api:4dc1977bf33581ee76440289061078eb-53ce4923-a8693ce4";
        final String url = "https://api.mailgun.net/v3/sandboxf2f0349e366f43aaab3722a7778e50b1.mailgun.org/messages";
        CloseableHttpClient client = HttpClients.createDefault();
        HttpPost httpPost = new HttpPost(url);
        httpPost.setHeader("Authorization", "Basic " + Base64.encodeBase64String(authStr.getBytes()));
        JSONObject data = new JSONObject();
        data.put("from", "postmaster@dypi.xyz");
        data.put("to", receiver);
        data.put("subject", subject);
        data.put("text", content);
        HttpEntity entity = new StringEntity(data.toJSONString(), ContentType.APPLICATION_JSON);
        httpPost.setEntity(entity);
        try(final CloseableHttpResponse response = client.execute(httpPost)) {
            return response.toString();
        } catch (Exception ignore) {
            //
        }

        return "";
    }
}
